package com.carman.cmreader;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSeekBar;

import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.thl.filechooser.FileChooser;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    private static final int SHOW_DIALOG = 0;
    private static final int DISMISS_DIALOG = 1;
    private static final int REFRESH_TXT = 2;

    private ProgressDialog dialog;
    private TextView tv_pageIndex;
    private VerticalSeekBar verticalSeekBar;
    private EditText et_searchCont,et_txt;
    private Spinner sp_searchType;


    private int curPage = 1;
    private int prePage = -1;
    private long firstClick;
    private boolean isFileLoaded = false;
    private boolean isPermissionGranted,isMatchCase;

    private ArrayList<String> list = new ArrayList<>();
    private TxtManager txtManager = new TxtManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        tv_pageIndex = findViewById(R.id.tv_pageIndex);
        et_searchCont = findViewById(R.id.et_searchCont);
        sp_searchType = findViewById(R.id.sp_searchType);
        verticalSeekBar = findViewById(R.id.verticalSeekBar);
        verticalSeekBar.setMax(100);

        et_txt = findViewById(R.id.et_txt);
        setAppVersion();

        initProgressDialog();

        String[] spinnerItems = {"Match Case","CompareNoCase"};
        ArrayAdapter<String> adapter_Q = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,spinnerItems);
        sp_searchType.setAdapter(adapter_Q);
        //设置spinner的选择监听事件
        sp_searchType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                isMatchCase = position == 0?true:false;
                txtManager.setMatchCase(isMatchCase);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        //支持seekbar拖动调整内容
        verticalSeekBar.setOnSeekBarChangeListener(new AppCompatSeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if(prePage == -1){
                    curPage = txtManager.getTotalPages()*progress/100;
                    prePage = curPage;
                }else {
                    curPage = txtManager.getTotalPages()*progress/100;
                }
                if(curPage == prePage){
                    return;
                }
                if(curPage == 0){
                    curPage = 1;
                }
                prePage = curPage;
                myHandler.sendEmptyMessage(REFRESH_TXT);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.i("carman","onStartTrackingTouch");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.i("carman","onStopTrackingTouch");
            }
        });

        //支持长按复制黏贴
        et_txt.setOnLongClickListener(v -> {
            ClipboardManager cm =(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
            cm.setText(et_txt.getText().toString());
            return false;
        });

       //请求读写存储权限
        requestPermissins(new PermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                isPermissionGranted = true;
            }

            @Override
            public void onPermissionDenied(String[] deniedPermissions) {
                Toast.makeText(MainActivity.this, "未获取到存储权限", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * Button事件处理
     * @param v
     */
    public void onBtnClickEvents(View v){

        switch(v.getId()){
            case R.id.btn_loadFile://加载文件
                if(!isPermissionGranted){
                    Toast.makeText(MainActivity.this, "未获取到存储权限", Toast.LENGTH_SHORT).show();
                    return;
                }

                //选择文件
                FileChooser fileChooser = new FileChooser(MainActivity.this, filePath -> {
                    ((EditText) findViewById(R.id.et_filePath)).setText(filePath);
                    new Thread(){
                        @Override
                        public void run() {

                            myHandler.sendEmptyMessage(SHOW_DIALOG);
                            txtManager.loadFile(filePath);
                            myHandler.sendEmptyMessage(DISMISS_DIALOG);
                            myHandler.sendEmptyMessage(REFRESH_TXT);
                            isFileLoaded = true;
                        }
                    }.start();

                });
                fileChooser.setBackIconRes(R.drawable.icon_arrow);
                fileChooser.setTitle("选择文件路径");
                fileChooser.setDoneText("确定");
                fileChooser.setThemeColor(R.color.colorAccent);
                fileChooser.open();

                //设置et_txt显示格式
                et_txt.setTextSize(13);
                et_txt.setGravity(Gravity.CLIP_HORIZONTAL);

                break;
            case R.id.btn_search://搜索
                if(!isFileLoaded){
                    Toast.makeText(MainActivity.this,"Load File First!",Toast.LENGTH_SHORT).show();
                    return;
                }

                String cont = et_searchCont.getText().toString();
                if(cont.length() > 0) {
                    txtManager.setKeyword(cont);
                }
                //触发显示内容
                new Thread(){
                    @Override
                    public void run() {
                        int ic = txtManager.getKwPageIndex(true, 0);
                        Log.i("carman","ic = " + ic);
                        if(ic != TxtManager.ERROR){
                            curPage = ic;
                            myHandler.sendEmptyMessage(REFRESH_TXT);
                        }
                    }
                }.start();
                break;
            case R.id.btn_clearSearchCont://清空搜索内容
                et_searchCont.setText("");
                txtManager.setKeyword(null);
                break;
            case R.id.btn_pre://逆向搜索
                if(!isFileLoaded){
                    Toast.makeText(MainActivity.this,"Load File First!",Toast.LENGTH_SHORT).show();
                    return;
                }
                //触发显示内容
                int ic = txtManager.getKwPageIndex(false,curPage-1);
                Log.i("carman","ic = " + ic);
                if(ic != TxtManager.ERROR) {
                    curPage = ic;
                    myHandler.sendEmptyMessage(REFRESH_TXT);
//                    verticalSeekBar.setProgress(curPage*100/txtManager.getTotalPages());
                }
                break;
            case R.id.btn_next://正向搜索
                if(!isFileLoaded){
                    Toast.makeText(MainActivity.this,"Load File First!",Toast.LENGTH_SHORT).show();
                    return;
                }
                //触发显示内容
                ic = txtManager.getKwPageIndex(true,curPage);
                Log.i("carman","ic = " + ic);
                if(ic != TxtManager.ERROR) {
                    curPage = ic;
//                    verticalSeekBar.setProgress(curPage*100/txtManager.getTotalPages());
                    myHandler.sendEmptyMessage(REFRESH_TXT);
                }
                break;
            case R.id.btn_pageDown://下一页
                if(!isFileLoaded){
                    Toast.makeText(MainActivity.this,"Load File First!",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(curPage < txtManager.getTotalPages()) {
                    curPage++;
                    myHandler.sendEmptyMessage(REFRESH_TXT);
                }
                break;
            case R.id.btn_pageUp://上一页
                if(!isFileLoaded){
                    Toast.makeText(MainActivity.this,"Load File First!",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(curPage > 1) {
                    curPage--;
                    myHandler.sendEmptyMessage(REFRESH_TXT);
                }
                break;
        }

    }

    private Handler myHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SHOW_DIALOG:
                    dialog.show();
                    break;
                case DISMISS_DIALOG:
                    dialog.dismiss();
                    break;
                case 2:
                    String cont = null;
                    try {
                        cont = txtManager.getPageCont(curPage-1);
                    }catch (ArrayIndexOutOfBoundsException e){
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this,"Reach Border",Toast.LENGTH_SHORT).show();
                        return;
                    }

                    et_txt.setText(Html.fromHtml(cont,Html.FROM_HTML_MODE_LEGACY));
                    tv_pageIndex.setText("Pages:(" + curPage + "/" + txtManager.getTotalPages() + ")");
                    break;

            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - firstClick > 2000L) {
                firstClick = System.currentTimeMillis();
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_LONG).show();
                return false;
            }
            finish();
            return true;
        }
        return false;
    }

    /**
     * 设置初始时Edittext版本信息
     */
    private void setAppVersion(){
        et_txt.setTextSize(53);
        et_txt.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);

        String cont = "CMReader \n";
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        try {
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            cont += "Histone @vers:" + packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        et_txt.setHint(cont);
    }

    /**
     * 加载文件时进度框
     */
    private void initProgressDialog(){
        // 默认效果是圆圈再转
        dialog = new ProgressDialog(this);
        // 设置进度条样式    水平和圆圈(当前这个是水平)
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setTitle("Loading File Contents....");
        // 设置最大进度
//        dialog.setMax(100);

        // 设置默认值
//        dialog.setProgress(1);
        // 设置进度值是否是不确定的
        dialog.setIndeterminate(true);
    }

    /**
     * 文件权限获取
     * @param mOnPermissionListener
     */
    private void requestPermissins(PermissionUtils.OnPermissionListener mOnPermissionListener) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mOnPermissionListener.onPermissionGranted();
            return;
        }
        String[] permissions = { "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
        PermissionUtils.requestPermissions(this, 0
                , permissions, mOnPermissionListener);
    }
}